package fr.sedoo.rbv.geonetwork.request;

import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;

public class SuggestRequest extends AbstractGeonetworkClient 
{
	private String fieldName;
	private List<String> suggestions;
	protected static final String UTF8 = "UTF8";
	
	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}
	
	public boolean execute() throws Exception
	{
		
		String url = getConfig().getSuggestURL()+getFieldName();
		
		GetMethod get = new GetMethod(url);
		try
		{
			int result = httpclient.executeMethod(get);
			
			if (result == HttpStatus.SC_OK)
			{
				InputStream responseBodyAsStream = get.getResponseBodyAsStream();
				StringWriter writer = new StringWriter();
				IOUtils.copy(responseBodyAsStream, writer, UTF8);
				String rawContent = writer.toString();
				JSONParser parser = new JSONParser();
				JSONArray globalArray = (JSONArray) parser.parse(rawContent);
				Iterator iterator = globalArray.iterator();
				while (iterator.hasNext()) 
				{
					Object object = iterator.next();
					if (object instanceof JSONArray)
					{
						JSONArray aux = (JSONArray) object;
						Iterator iterator2 = aux.iterator();
						List<String> suggestions = new ArrayList<String>();
						while (iterator2.hasNext()) 
						{
							Object object2 = (Object) iterator2.next();
							suggestions.add(object2.toString());
						}
						this.setSuggestions(suggestions);
					}
					
					
				}
				
				
				return true;
			}
			else
			{
				return false;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
	    	return false;
	    }
	    finally {
	    	get.releaseConnection();
	      }
		
		
		
		
	}

	public List<String> getSuggestions() {
		return suggestions;
	}

	public void setSuggestions(List<String> suggestions) {
		this.suggestions = suggestions;
	}
	
	
}
